package com.xq.chrome.web.controller;


import com.xq.chrome.web.other.conf.ServerConfig;
import com.xq.chrome.utils.ProxyUtils;
import com.xq.chrome.utils.ValidateUtil;
import org.codehaus.plexus.util.StringInputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 翻译工具类的总入口
 *
 * @author MACHENIKE
 */
@RestController
@RequestMapping("see")
public class MainController {


  /**
   * 使用value注入属性
   * @param port
   * @return
   */
  @RequestMapping("/port")
  public int port(@Value("${server.port}") int port) {
    return port;
  }

  @Autowired
  private Environment env;
  @Autowired
  private ServerConfig config;

  @RequestMapping("/sConf")
  public @ResponseBody
  Map<String, String> systemConfig() {
    Map<String, String> map = new HashMap<String, String>();
    map.put("user.dir", env.getProperty("user.dir"));
    map.put("user.home", env.getProperty("user.home"));
    map.put("JAVA_HOME", env.getProperty("JAVA_HOME"));
    map.put("server.port", env.getProperty("server.port"));
    map.put("serverConfig", config.toString());
    return map;
  }


  @RequestMapping("/world")
  public String indexHtml() {
    return "hello world";
  }

  /**
   * 翻译文档
   *
   * @param url
   * @param request
   * @param response
   * @return
   * @throws IOException
   */
  @RequestMapping("/do1")
  public String doWork(@RequestParam("url") String url, HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {
      System.out.println(url);
      if (!ValidateUtil.validateUrl(url)) {
        return "您输入的不是正确的url";
      }
      String path = request.getContextPath();
      String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
      String html = new ProxyUtils().getUrlMap(url, basePath);
//            return html;
      InputStream is = new StringInputStream(html);
      BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
      String line;
      PrintWriter out = response.getWriter();
      while ((line = in.readLine()) != null) {
        out.println(line);
      }
      out.flush();
      in.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 使用GET提交到目标服务器。
   *
   * @param request
   * @param response
   * @param targetUrl
   * @throws IOException
   */
  @RequestMapping("/forward")
  public Object urlRedirect(@RequestParam("yeekit_proxy_url") String targetUrl, HttpServletRequest request, HttpServletResponse response) throws IOException {

    if (targetUrl.endsWith(".htm") || targetUrl.endsWith(".html") || targetUrl.endsWith(".shtml")) {
      try {

        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";

        String html = new ProxyUtils().getUrlMap(targetUrl, basePath);
//                return html;
        InputStream is = new StringInputStream(html);
        BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        String line;
        PrintWriter out = response.getWriter();
        while ((line = in.readLine()) != null) {
          out.println(line);
        }
        out.flush();
        in.close();
      } catch (Exception e) {
        e.printStackTrace();
//                return null;
      }

    } else if (targetUrl.endsWith(".css") || targetUrl.endsWith(".js") || targetUrl.endsWith(".jpg") ||
        targetUrl.endsWith(".png") || targetUrl.endsWith(".svg") || targetUrl.endsWith(".gif")) {
      String fileName = targetUrl.split("/")[targetUrl.split("/").length - 1];
//            response.setHeader("Content-Disposition", "attachment; filename="
//                    + java.net.URLEncoder.encode(fileName, "UTF-8"));
      //图片的名称
      String imgName = fileName;
      //名称转码，避免中文乱码
      imgName = new String(imgName.getBytes("iso8859-1"), "UTF-8");
      //图片的资源地址，http://10.80.3.229:8081/mediaserver/574fe515e30ab97c9068d2e1
      //这是媒体服务器返回的地址，因为是网络地址，所以需要使用HttpURLConnection去获取图片
      String imgUrl = targetUrl;
      //输入流，用来读取图片
      InputStream ins = null;
      HttpURLConnection httpURL = null;
      try {
        URL url = new URL(imgUrl);
        //打开一个网络连接
        httpURL = (HttpURLConnection) url.openConnection();
        //设置网络连接超时时间
        httpURL.setConnectTimeout(3000);
        //设置应用程序要从网络连接读取数据
        httpURL.setDoInput(true);
        //设置请求方式
        httpURL.setRequestMethod("GET");
        //获取请求返回码
        int responseCode = httpURL.getResponseCode();
        if (responseCode == 200) {
          //如果响应为“200”，表示成功响应，则返回一个输入流
          ins = httpURL.getInputStream();
          //设置response响应头
          //encodeChineseDownloadFileName()用来解决文件名为中文的问题，方法体在下面
          if (fileName.indexOf(".css") > -1) {
            response.setContentType("text/css");
          }
          response.setHeader("content-disposition", "attachment;filename=" + ProxyUtils.encodeChineseDownloadFileName(request, imgName));
          //输出流到response中
          byte[] data = new byte[1024];
          int len = 0;
          //输出流
          OutputStream out = response.getOutputStream();
          while ((len = ins.read(data)) > 0) {
            out.write(data, 0, len);
          }
          out.flush();
          ins.close();

        }
      } catch (Exception e) {
        System.out.println("下载附件图片出错！" + targetUrl);
        e.printStackTrace();
      }
    }
    return null;
  }
}
